import { HttpGet } from "@/network/servers"
import { useEffect, useRef } from "react"
import {
    getBrowserController,
    getNet,
    getStorage,
    getWxSDKParams
} from '@/pages/components/utils';
import md5 from 'md5'
import qs from 'qs'
import _ from 'lodash'
import Utils from "./index";

let wx = require('weixin-js-sdk')
const browserController = getBrowserController()
const net = getNet()

export const useDocumentTitle = (title: string, onPageUnmount: boolean = true) => {
    let oldTitle = useRef(document.title).current

    useEffect(() => {
        document.title = title
    }, [title])

    useEffect(() => {
        return () => {
            if (!onPageUnmount) {
                document.title = oldTitle
            }
        }
    }, [])

}


export const getAccessToken = (sysId: string) => {
    return md5(sysId).split('').reverse().join('')
}

/**
 * 
 * @param baseAddr 基础平台地址
 * @param sysId 系统地址 默认使用基础平台
 * @param token 用户token
 * 
 */

export const useGetUserInfo = async (baseAddr: string, sysId: string = '000', token: string) => {
    let result = await HttpGet({
        url: baseAddr + '/BaseApi/Login/GetOnlineUserInfo',
        data: {
            appid: sysId,
            access_token: getAccessToken(sysId),
            token
        },
        load: true
    })

    let userInfo = result.Data
    return userInfo
}

/**
 * 向url上添加参数
 * @param url 需要转换参数的url
 * @param params 添加的参数对象
 */
export const useTransformUrl = (url: string, params: object) => {
    if (url.indexOf('schoolId') > -1 && url.indexOf('env') > -1) {  //已经携带schoolId，不再处理
        return url
    }
    if (!url.includes('#')) {
        if (url.includes('?')) {
            return `${url}&${qs.stringify(params)}`
        } else {
            return `${url}?${qs.stringify(params)}`
        }
    }
    let paramList = url.split('#')
    let newUrl: any = []

    if (Array.isArray(paramList) && paramList.length > 0) {
        for (let i = 0; i < paramList.length; i++) {
            let item = paramList[i]
            if (i == 0) {
                if (paramList[i].includes('?')) {
                    item += `&${qs.stringify(params)}`
                } else {
                    item += `?${qs.stringify(params)}`
                }
            }
            newUrl.push(item)
        }
    }

    // console.log(url, params, paramList, newUrl.join('#'))
    return newUrl.join('#')
}

export const useGetFileName = (fileName: string) => {
    if (!fileName) {
        return '文件'
    }

    let pot1 = fileName.lastIndexOf('.')
    return fileName.substring(0, pot1)
}

/**
 * 
 * @param url 文件下载地址
 * @param fileName 文件名
 * @param file 文件
 * 
 */
export const useDownloadFile = (url: string, fileName: string, file: any): any => {
    let name = useGetFileName(fileName)
    return new Promise(async (resolve, reject) => {
        if (Utils.getSystemInfo() === 'weapp') {
            const params = await getWxSDKParams([])
            wx.config(params);
            try {
                browserController.openFileForWebview(wx, { fileUrl: url, fileName: name })
                resolve(file)
            } catch (error) {
                Taro.showToast({ title: error, icon: 'none' })
            }
        } else {
            net.downloadFile({
                url,
                fileName,
                onProgress: process => {
                    Taro.showToast({
                        icon: 'loading',
                        title: `正在下载${process}`
                    })
                },
                onSuccess: path => {
                    Taro.showToast({
                        title: '下载成功',
                        icon: 'success',
                        duration: 2000
                    })
                    resolve(path)
                },
                onError: error => {
                    Taro.showToast({
                        title: '下载失败',
                        icon: 'none',
                        duration: 2000
                    })
                    reject(error)
                }
            })
        }
    })
}

/**
 * 判断当前是否为数组类型，且不为空
 * @param arr 需要判断为数组的数据
 * @returns boolean 
 */
export const useGetIsMapArray = (arr) => {
    return _.isArray(arr) && arr.length > 0
}

/**
 * 发送websocket 信息
 * @param data 发送的数据对象
 */
export const useSendSocketMsg = (data) => {
    if (window.chatSocket && window.chatSocket.readyState == '1') {
        window.chatSocket.send(JSON.stringify(data))
    }
}

/**
 * 获取当前webSocket链接类型
 * @returns {Number} ClientType
 */
export const useGetClientType = () => {
    if (Utils.getSystemInfo() === 'weapp') {
        return 2
    } else {
        return 3
    }
}

/**
 * 获取系统地址的ip和端口
 * @param url 传入的路径 如http://120.196.79.139:22101/lg_im/
 * @returns 
 */
export const useGetIpAndPort=(url)=> {
    const parsedUrl = new URL(url);
    const ip = parsedUrl.hostname;
    const port = parsedUrl.port;
    return `${ip}:${port}`
  }

  /**
 * 在线检测方法
 * @param url 基础平台地址
 * @param token 用户token
 * @param sysId 当前系统id
 * @param callback 回调函数
 */
export const useOnlineCheck = (url, token, sysId, callback?) => {
    if (Utils.getSystemInfo() === 'h5') { //只有在app时才调用
        const script = document.createElement('script')
        script.setAttribute('src', `${url}/JS/mobile-check-online.min.js`)
        document.head.appendChild(script)
        script.addEventListener('load', () => {
            window.lgCheckOnline(url, token, sysId, callback)
        })
    }
}